<?php
/**
 * Created by PhpStorm.
 * User: cc
 * Date: 2024/3/15
 * Time: 16:03
 */

namespace app\zyhsmarketing\lib;

use app\zyhsapi\model\marketing\ZyhsMarketingCallbackRecode;
use think\Db;
use think\Env;
use XznsTools\curl\Curl;

class XmMarketing
{
    private $marketingCallbackConfig = [
        1 => [
            'encrypt_key' => 'gcwCpGolzLhOGYWA',
            'sign_key' => 'ddnyIoblXbPjGWPj',
        ],
        2 => [  // 自定义 注册
            'encrypt_key' => 'PmjkMkpscgyhNKBx',
            'sign_key' => 'kRkwTYvDzuSuYWhd',
        ],
        3 => [  // 充值
            'encrypt_key' => 'BRBvSbhoMSYIhvKB',
            'sign_key' => 'MRcVfjGCTUjAhDUs',
        ],
    ];

    public $appId = '1572265';
    public $customerId = '555602';
    public $testUrl = 'http://trail.e.mi.com/global/test';
    public $onlineUrl = 'http://trail.e.mi.com/global/log';


    /**
     * 小米 回传
     * @param string $oaid
     * @param int $uid
     * @param int $targetType 1 =>激活 2=>注册 3=>充值
     * @return void
     */
    public function callBack(string $oaid, int $uid, int $targetType)
    {
        if (!in_array($targetType, [1, 2], true))
        {
            return;
        }
        $zyhsMarketingCallbackRecodeModel = new ZyhsMarketingCallbackRecode();
        // 根据文档填写必填参数
        $nowTime = time();
        // 注意！设备信息必须按照文档顺序填写否则会sign校验失败
        $d = [
            "oaid" => $oaid,
            "conv_time" => $nowTime * 1000,
        ];
        $ua = request()->header('user-agent');
        if ($ua)
        {
            $d['client_ip'] = request()->ip();
            $d['ua'] = $ua;
        }
        $final_info = $this->build_info($d, $this->marketingCallbackConfig[$targetType]['sign_key'], $this->marketingCallbackConfig[$targetType]['encrypt_key']);

        $url = Env::get('host.name') === 'online' ? $this->onlineUrl : $this->testUrl;

        switch ($targetType)
        {
            case 2: // 注册
                $convType = 'APP_REGISTER';
                break;
            case 3: // 充值
                $convType = 'APP_PAY';
                break;
            default:    // 激活
                $convType = 'APP_ACTIVE_NEW';
        }

        $resData = Curl::request($url, [
            'appId' => $this->appId,
            'info' => $final_info,
            'conv_type' => $convType,//自定义注册
            'customer_id' => $this->customerId,
        ], 'GET');
        if (!$resData['success'] || !isset($resData['data']['success']) || !$resData['data']['success'])
        {   // 回传失败
            Db::table('good_wechat.zyhs_marketing_callback_error')->insert([
                'mobile_type' => 4, // 华为=>5 小米=>4 vivo=>3 oppo=>2
                'target_type' => $targetType,
                'oaid' => $oaid,
                'extend' => json_encode($resData, JSON_UNESCAPED_UNICODE),
            ]);
        } else
        {
            // 添加 回传 记录
            $zyhsMarketingCallbackRecodeModel->insert([
                'task_id' => '',
                'oaid' => $oaid,
                'uid' => $uid,
                'type' => 4,    // 终端类型 华为=>5 小米=>4 vivo=>3 oppo=>2
                'target_type' => $targetType,
                'create_time' => $nowTime,
            ]);
        }
    }


    /**
     * 拼装请求参数
     * @param $device
     * @param $sign_key
     * @param $encrypt_key
     * @return string
     */
    public function build_info($device, $sign_key, $encrypt_key)
    {
        // queryString 设备信息
        $query_string = http_build_query($device);
        // md5后的sign值
        $sign = md5($sign_key . "&" . urlencode($query_string));
        // baseData
        $base_data = $query_string . "&sign=" . urlencode($sign);
        return $this->encrypt($base_data, $encrypt_key);
    }


    /**
     * 参数加密
     * @param $baseData
     * @param $key
     * @return string
     */
    public function encrypt($baseData, $key)
    {
        $l1 = strlen($baseData);
        $l2 = strlen($key);
        $res = '';
        for ($i = 0; $i < $l1; $i++)
        {
            $res .= $baseData[$i] ^ $key[$i % $l2];
        }
        return urlencode(base64_encode($res));
    }
}
